<template>
  <div class="edit-container">
    <!-- 导航条 -->
    <van-nav-bar
      left-arrow
      @click-left="$router.go(-1)"
      title="编辑资料"
    ></van-nav-bar>
    <!-- 头像部分 -->
    <div class="avatar">
      <!-- 展示头像 -->
      <van-image
        fit="cover"
        width="120px"
        height="120px"
        round
        :src="userInfo.photo"
      />
      <!-- 图片上传 -->
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 信息展示 -->
    <van-cell-group>
      <van-cell
        is-link
        title="名称"
        :value="userInfo.name"
        @click="showDialogClick"
      />
      <van-cell
        is-link
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
        @click="showPopup = true"
      />
      <van-cell
        is-link
        title="生日"
        :value="userInfo.birthday"
        @click="showDatePicker"
      />
    </van-cell-group>

    <!-- 修改昵称的对话框 -->
    <van-dialog
      v-model="showDialog"
      title="修改昵称"
      show-cancel-button
      @confirm="updateNickname"
    >
      <van-field
        ref="nameFiled"
        placeholder="请输入昵称"
        v-model="newName"
      ></van-field>
    </van-dialog>

    <!-- 修改性别 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        left-arrow
        @click-left="showPopup = false"
      >
      </van-nav-bar>
      <van-cell is-link title="男" @click="updateGender(0)" />
      <van-cell is-link title="女" @click="updateGender(1)" />
    </van-popup>

    <!-- 修改生日 -->
    <van-popup v-model="showDate" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="updateDate"
        @cancel="showDate = false"
      />
    </van-popup>

    <!-- 图片裁剪盒子 -->

    <!-- 裁切区域弹框 -->
    <div class="cropper-box" v-show="showCropper">
      <!-- 裁切组件 -->
      <vueCropper
        ref="cropper"
        fixed
        autoCropWidth="120"
        autoCropHeight="120"
        autoCrop
        :img="img"
        canScale
      ></vueCropper>
      <van-button @click="submitPhoto" class="confirm-btn" type="primary"
        >确认</van-button
      >
      <van-button @click="showCropper = false" class="cancel-btn" type="info"
        >取消</van-button
      >
    </div>
  </div>
</template>

<script>
// 导入mapState辅助函数
import { mapState } from 'vuex'
import { editUserInfo, editUserAvatar } from '@/views/user/user.js'
import { VueCropper } from 'vue-cropper'
import moment from 'moment'

export default {
  name: 'edit',
  data () {
    return {
      showDialog: false, // 编辑姓名弹框
      newName: '',
      newBirthday: '',
      showPopup: false,
      showDate: false,
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      img: '', // 要裁剪的图片
      showCropper: false
    }
  },
  components: {
    VueCropper
  },
  computed: {
    // mapState会自动生成计算属性（跟下面写法一样）
    // 映射 this.userInfo 为 store.state.userInfo
    ...mapState(['userInfo'])

    // userInfo () {
    //   return this.$store.state.userInfo
    // }
  },
  methods: {
    // 输入框自动聚焦
    showDialogClick () {
      this.showDialog = true
      this.newName = this.userInfo.name
      // 异步渲染 等当前异步渲染DOM结束之后执行
      this.$nextTick(() => {
        this.$refs.nameFiled.focus()
      })
    },
    // 更新名字
    updateNickname () {
      if (this.newName == '') return
      editUserInfo({ name: this.newName }).then(res => {
        console.log(res)
        // 弹窗显示更新成功
        this.$toast.success('更新成功')
        // 更新vuex的数据
        this.$store.commit('setUserInfo', {
          //先传入原始数据
          ...this.userInfo,
          //然后使用新的name覆盖原始的name
          name: this.newName
        })
      })
    },

    // 更新性别
    updateGender (gender) {
      editUserInfo({ gender }).then(res => {
        console.log(res)
        // 弹窗显示更新成功
        this.$toast.success('更新成功')
        // 更新vuex的数据
        this.$store.commit('setUserInfo', {
          //先传入原始数据
          ...this.userInfo,
          //然后使用新的gender覆盖原始的gender
          gender
        })
        // 关闭弹窗 popup弹窗默认是点击空白区域关闭。我们点击的是cell需要手动关闭
        this.showPopup = false
      })
    },

    // 生日弹框
    showDatePicker () {
      this.showDate = true
      this.currentDate = new Date(this.userInfo.birthday)
    },

    // 更新生日
    updateDate () {
      // console.log(this.currentDate)
      let birthday = moment(this.currentDate).format('YYYY-MM-DD')
      editUserInfo({ birthday }).then(res => {
        // console.log(res)
        this.$toast.success('更新成功')
        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          birthday
        })
        this.showDate = false
      })
    },

    // 上传头像
    afterRead (file) {
      this.img = file.content
      this.showCropper = true
    },

    // 裁切确认
    submitPhoto () {
      // 获取截图的blob数据
      this.$refs.cropper.getCropBlob(blob => {
        let fd = new FormData()
        fd.append('photo', blob)
        // 此时可以自行将文件上传至服务器
        editUserAvatar(fd).then(res => {
          // console.log(res)
          this.$toast.success('更新成功')
          // 更新vuex数据
          this.$store.commit('setUserInfo', {
            ...this.userInfo,
            photo: res.data.data.photo
          })
          // 关闭裁剪窗口
          this.showCropper = false
        })
      })
    }
  }
}
</script>

<style lang="less">
.avatar {
  display: flex;
  height: 160px;
  justify-content: center;
  align-items: center;
  .van-uploader {
    opacity: 0;
    position: absolute;
    width: 125px;
    height: 125px;
    .van-uploader__upload {
      width: 120px;
      height: 120px;
    }
  }
}

// 裁切弹框样式
.cropper-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  .confirm-btn {
    position: absolute;
    left: 0;
    bottom: 0;
  }
  .cancel-btn {
    position: absolute;
    right: 0;
    bottom: 0;
  }
}
</style>
